import cloud from '@lafjs/cloud'
let dbName = "web-course"
const db = cloud.database();

export default async function (ctx: FunctionContext) {
  let { type } = await cloud.nw.db.findByWhereJson({
    dbName,
    whereJson: { _id: ctx.body.courseId },
  });

  let { data } = await db.collection(dbName).get()
  let arr = []
  data.forEach(element => {
    if (element.type.includes(type[0]) && element.status == 1) {
      arr.push(element)
    }
  });
  return cloud.utils.requestReturn({ data: getRandomData(arr) })
}

function getRandomData(jsonArray) {
  if (jsonArray.length < 4) return jsonArray;

  // 创建一个新数组来存储随机选取的元素
  var randomData = [];
  var index;

  // 循环四次，每次选择一个随机索引
  for (var i = 0; i < 4; i++) {
    do {
      index = Math.floor(Math.random() * jsonArray.length);
    } while (randomData.includes(jsonArray[index])); // 确保不会选取到重复的元素
    randomData.push(jsonArray[index]);
  }

  return randomData;
}
